import {ref, reactive, onMounted} from 'vue'
import {message} from "ant-design-vue";
import {AccountService} from "@/views/erp/system/account/accountService";
import validate from "ele-admin-pro/packages/validate";


export default function AccountMapSelect(props) {
  //当前业务
  const business = reactive({businessId: props.businessId, entityName: props.entity});

  //选择器数据
  let selectObj = ref("银行卡号(账户名称)")

  //选项列表
  const options = ref([])

  //账户信息列表
  const accountList = ref([])
  //账户信息码表,便于选中后展示。
  const accountMap = reactive({});
  //选中的对象
  const accountEntity = ref({label: ''})

  //选中的关键字
  const selectKey = ref(null);

  //新增的实体，用于修改，每次新增之后不会新增一条新数据，
  // 而是在新增的那个选项进行更改。
  // 如果没有新增选项就直接在选址列表中添加该对象。
  const insertEntity = reactive({
    name: '',
    entityName: business.entityName,
    businessId: business.businessId,
    bank: '',
    bankAccount: ''
  })

  //弹窗显示
  const flagCollection = reactive({showEdit: false})

  //弹窗表格对象
  const accountForm = ref({})

  onMounted(() => {
    reload()
    console.log("accountForm", accountForm.value)
  })


  const reload = () => {

    const conditions = {
      entityName: business.entityName,
      businessId: business.businessId,
      status: "启用"
    }

    const queryParams = {}
    //获取筛选结果（无懒加载）
    queryParams.filters = conditions
    options.value = []
    accountList.value = []

    AccountService.findAccounts(queryParams).then((res) => {
      console.log("findAccounts", res)
      accountList.value = res.data.datas;
      //打包选项
      packOptions();
    }).catch((error) => {
      message.error(error.message);
    })

  }

  //页面加载时的打包所有选项
  const packOptions = () => {
    let list = accountList.value;
    let optionList = options.value;

    for (let i = 0; i < list.length; i++) {
      list[i].label = list[i].bankAccount + "(" + list[i].name + ")"
      optionList.push({value: list[i].eid, label: list[i].label})
      accountMap[list[i].eid] = list[i];
    }
  }

  //选项修改事件
  const handleAccountChange = (value) => {
    if (accountMap[value]) {
      //选择的时数据库存储实体
      accountEntity.value = accountMap[value]
      selectKey.value = accountMap[value].eid
    } else {
      //初始化
      accountEntity.value = {label: ''}
      selectKey.value = ""
    }
    console.log(accountEntity)
    console.log(value)
    reload()
  }

  //新增账户的修改事件
  const editEvent = () => {
    flagCollection.showEdit = true
  }

  //用于保存新增的账户结果到选项中。
  const saveOption = () => {
    // console.log(insertEntity)

    // let vaildMessage = validate.bankAccountValid(insertEntity.bankAccount)
    // if (vaildMessage !== "账户校验成功") {
    //   message.error(vaildMessage)
    //   return;
    // }


    insertEntity.label = insertEntity.bankAccount + "(" + insertEntity.name + ")"
    selectObj.value = insertEntity.label
    insertEntity.status = "启用"

    AccountService.saveAccount(insertEntity).then((res) => {
      console.log(res);
      selectObj.value = insertEntity.label
      accountEntity.value = insertEntity
      message.success("新增成功")

      cancelFn();

    }).catch((error) => {
      message.error(error.message)
    })

  }


  //银行卡卡号表单验证
  let validateBankAccount = async (rule, value) => {

    let msg = validate.bankAccountValid(value)
    if (msg !== "账户校验成功") {
      return Promise.reject(msg)
    }

    let list = accountList.value

    //验证唯一性
    console.log("tempList", list)
    for (let i = 0; i < list.length; i++) {
      console.log("account", list)
      if (list[i].bankAccount === insertEntity.bankAccount) {
        return Promise.reject("银行账号重复，请确认填写是否正确");
      }
    }

    console.log(value)
    return Promise.resolve()
  }


  const rules = reactive({
    name: [
      {required: true, message: '账户名称必须输入', trigger: "onSubmit"},
    ],
    bank: [
      {required: true, message: "银行名称必须输入", trigger: "onSubmit"}
    ],
    bankAccount: [
      {required: true, message: "银行卡号必须输入", trigger: "onSubmit"},
      {
        validator: validateBankAccount, trigger: "onSubmit"
      }]
  })

  //取消按钮事件
  let cancelFn = () => {
    flagCollection.showEdit = false;
    reload()
  }
  //获取对应选中的数据
  const getOption = () => {
    console.log("value", accountEntity.value)
    return accountEntity.value
  }


  const onSubmit = () => {
    accountForm.value.validate().then(
      () => {
        console.log("submit")
        saveOption()

      }
    ).catch((error) => {
      console.log("error", error)
    })

    // saveOption()

  }

  return {
    accountForm,
    onSubmit,
    business,
    rules,
    insertEntity,
    flagCollection,
    selectObj,
    accountEntity,
    options,
    cancelFn,
    packOptions,
    handleAccountChange,
    editEvent,
    saveOption,
    getOption,
  }

}

